package com.sikao.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 拍卖下单页面
 */
import com.sikao.app.R;
import com.sikao.app.bean.AddAuctionLogBean;
import com.sikao.app.bean.AddAuctionLogSubmitBean;
import com.sikao.app.bean.BeforeAuctionBean;
import com.sikao.app.bean.BeforeAuctionSubmitBean;
import com.sikao.app.bean.CalculateMarginBean;
import com.sikao.app.bean.CalculateMarginSubmitBean;
import com.sikao.app.dao.AddAuctionLogModel;
import com.sikao.app.dao.BeforeAuctionModel;
import com.sikao.app.dao.CalculateMarginModel;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.ui.base.BaseActivity;
import com.sikao.app.utils.ConstantClass;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.utils.Utils;

public class AuctionOrderActivity extends BaseActivity implements View.OnClickListener {

    private TextView titleTv;
    private ImageView backIv;
    private TextView tvNowPrice;
    private TextView tvLeastAddPrice;
    private TextView tvMargin;
    private EditText etMyPrice;
    private LinearLayout llMargin;


    private Button orderBtn;

    private String auctionId = "";

    private String buy_margin = "";
    private boolean is_margin = false;
    private BeforeAuctionBean beforeAuctionBean;
    private  CalculateMarginBean calculateMarginBean;
     private String money ="";
    private String payPassword = "";
    public static final int PAY_REQUEST_CODE = 10002;//保证金付款请求的code
    public static final int PAY_RESULT_CODE = 100020;//保证金付款正常返回的code

    //String cash = "0.00";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_auction_order);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initData() {
        auctionId = getIntent().getStringExtra("auctionId");
        //money  = getIntent().getStringExtra("money");
        buy_margin = getIntent().getStringExtra("buy_margin");
        Toast.makeText(this, " auctionId=" + auctionId, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void initView() {
        titleTv = (TextView) findViewById(R.id.title_middle_tv);
        backIv = (ImageView) findViewById(R.id.title_left_img);
        tvNowPrice = (TextView) findViewById(R.id.tv_now_price);
        tvLeastAddPrice = (TextView) findViewById(R.id.tv_least_add_price);
        tvMargin = (TextView) findViewById(R.id.tv_margin);
        etMyPrice = (EditText) findViewById(R.id.et_my_price);
        llMargin = (LinearLayout) findViewById(R.id.ll_margin);
        orderBtn = (Button) findViewById(R.id.order_btn);

        beforeAuction();

    }


    private void initViewData() {
        if (is_margin) {//已经交过保证金
            llMargin.setVisibility(View.GONE);
            orderBtn.setText("加价拍卖");
        } else {
            //计算保证金
            calculateMargin();
            tvMargin.setText(buy_margin);
            orderBtn.setText("交保证金并参加拍卖");
        }
        // 设置当前报价 最低加价金额
        tvNowPrice.setText(beforeAuctionBean.getRes().getMax_amoutn() + "");
        tvLeastAddPrice.setText(beforeAuctionBean.getRes().getLeast_add() + "");
        etMyPrice.setText(beforeAuctionBean.getRes().getThis_price());


    }

    private void beforeAuction() {
        BeforeAuctionSubmitBean beforeAuctionSubmitBean = new BeforeAuctionSubmitBean();
        beforeAuctionSubmitBean.setAuctionId(auctionId + "");

        new BeforeAuctionModel(this, new OnNetBackListener<BeforeAuctionBean>() {
            @Override
            public void netBack(BeforeAuctionBean data) {
                if (data == null) {
                    Toast.makeText(AuctionOrderActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                } else {
                    if (data.getStatus() == 1) {
                        beforeAuctionBean = data;
                        if ("0".equals(data.getRes().getIs_margin())) {//没有交过保证金
                            is_margin = false;
                        } else if ("1".equals(data.getRes().getIs_margin())) {//交过保证金
                            is_margin = true;
                        }
                        initViewData();

                    } else {
                        Toast.makeText(AuctionOrderActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }


        }).request(JSONUtil.toJSON(beforeAuctionSubmitBean), true);
    }

    @Override
    protected void initListener() {
        backIv.setOnClickListener(this);
        orderBtn.setOnClickListener(this);
        etMyPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!is_margin){
                    calculateMargin();
                }

            }
        });
    }

    @Override
    protected void init() {
        titleTv.setText("立即下单");
        backIv.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_img:
                finish();
                break;
            case R.id.order_btn:
                //买家出价
                if (is_margin) {
                    addAuctionLog();
                } else {
                    payCheck();
                }
                break;
            default:
                break;
        }
    }

    private void payCheck() {
        if (TextUtils.isEmpty(etMyPrice.getText())) {
            Utils.showToast("出价金额不能为空");
            return;
        }

        Intent intentPay = new Intent();
        intentPay.setClass(this, PayForReleaseGoodsActivity.class);

        intentPay.putExtra("publishType", 2);
        //保证金的
        intentPay.putExtra("geld", Utils.roundForNumber(tvMargin.getText().toString(), 2));
        intentPay.putExtra("balance", Utils.roundForNumber(ConstantClass.balanceValue+"", 2));

        startActivityForResult(intentPay, PAY_REQUEST_CODE);
    }

    private void addAuctionLog() {

        if (TextUtils.isEmpty(etMyPrice.getText())) {
            Utils.showToast("出价金额不能为空");
            return;
        }
       /* if (Utils.isNumber(etMyPrice.getText().toString())){
            Utils.showToast("出价金额需要是数字");
            return;
        }*/


//{"auctionId":"108","payPassword":"123456","margin":"100.00","price":"1000.00"}
        AddAuctionLogSubmitBean addAuctionLogSubmitBean = new AddAuctionLogSubmitBean();
        addAuctionLogSubmitBean.setAuctionId(auctionId);
        if (is_margin) {
            addAuctionLogSubmitBean.setPayPassword("");
            addAuctionLogSubmitBean.setMargin("0.00");
        } else {
            addAuctionLogSubmitBean.setPayPassword(payPassword);
            addAuctionLogSubmitBean.setMargin(Utils.roundForNumber(buy_margin, 2));
        }
        addAuctionLogSubmitBean.setPrice(Utils.roundForNumber(etMyPrice.getText().toString(), 2));

        new AddAuctionLogModel(this, new OnNetBackListener<AddAuctionLogBean>() {
            @Override
            public void netBack(AddAuctionLogBean data) {
                if (data == null) {
                    Toast.makeText(AuctionOrderActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                } else {
                    if (data.getStatus() == 1) {

                        Toast.makeText(AuctionOrderActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                        //重新加载
                        beforeAuction();
                    } else {
                        Toast.makeText(AuctionOrderActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }).request(JSONUtil.toJSON(addAuctionLogSubmitBean), true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PAY_REQUEST_CODE://是付款返回的
                if (resultCode == PAY_RESULT_CODE) {//正常付款返回的
                    payPassword = data.getStringExtra("payPassword");
                    addAuctionLog();
                }
                break;
        }
    }
     	private void calculateMargin() {
		//{"role":"buyer","type":"auction","money":"","objId":""}
             money = etMyPrice.getText().toString();
            if (!Utils.isNumber(money)) {
                return;
            }

		CalculateMarginSubmitBean calculateMarginSubmitBean = new CalculateMarginSubmitBean();
		calculateMarginSubmitBean.setRole("buyer");
		calculateMarginSubmitBean.setType("auction");
		calculateMarginSubmitBean.setMoney(money);
		calculateMarginSubmitBean.setObjId(auctionId+"");

		new CalculateMarginModel(this, new OnNetBackListener<CalculateMarginBean>() {
			@Override
			public void netBack(CalculateMarginBean data) {
				if (data == null) {
					Toast.makeText(AuctionOrderActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {
						calculateMarginBean=data;
                        buy_margin=calculateMarginBean.getRes().getMargin();
                        tvMargin.setText(buy_margin+"");
					} else {
						Toast.makeText(AuctionOrderActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		}).request(JSONUtil.toJSON(calculateMarginSubmitBean),true);

	}
}
